#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import configparser
from flask import Flask, jsonify, request
from flask_cors import CORS
from wsgiref.simple_server import make_server, WSGIRequestHandler


# 读取配置文件
port = 5000
try:
    cf = configparser.ConfigParser()
    cf.read("./config.ini", encoding='utf-8')
    port = cf.get("config", "port")
except Exception as e:
    print("读取配置文件异常：%s" % (e))


# Flask & CORS
app = Flask(__name__)
CORS(app, resources=r'/*')


# 示例接口
@app.route('/api/example', methods=['GET', 'POST'])
def face_compare():
    # 获取参数1
    if request.method == "GET":
        param1 = request.args.get("param1")
    elif request.method == 'POST':
        param1 = request.form.get("param1")
        file1 = request.files.get("file1")
    
    # 获取参数2
    # getArgs = request.args
    # postForm = request.form

    # 返回结果
    return build_api_result(0, "message", "data")


# 构建接口返回结果
def build_api_result(code, message, data):
    result = {
        "code": code,
        "message": message,
        "data": data
    }
    print("Response Data: ", result)
    return jsonify(result)


# 自定义请求处理（取消日志打印）
class NoLoggingWSGIRequestHandler(WSGIRequestHandler):
    def log_message(self, format, *args):
        pass


if __name__ == "__main__":
    # Json config
    app.config['JSON_AS_ASCII'] = False
    
    # WSGI simple run
    httpd = make_server('', int(port), app, handler_class = NoLoggingWSGIRequestHandler)
    print("Serving HTTP on port " + port + "...")
    httpd.serve_forever()